<template>
  <view class="list-page">
    <!-- 搜索栏 -->
    <view class="list-search-bar">
      <view class="list-search-input">
        <uni-icons type="search" size="16" color="#999"></uni-icons>
        <input v-model="queryParams.dictName" class="list-input" placeholder="搜索字典名称、字典类型"
               @input="handleSearchInput" @confirm="handleSearch"/>
        <uni-icons v-if="queryParams.dictName" type="clear" size="16" color="#999" @click="handleClear"></uni-icons>
      </view>
      <view class="list-filter-btn" @click="toggleFilter">
        <uni-icons type="filter" size="14" color="#666"></uni-icons>
        <text>筛选</text>
      </view>
    </view>

    <!-- 筛选抽屉 -->
    <uni-popup ref="filterPopup" type="right" :mask-click="false">
      <view class="list-filter-drawer">
        <view class="list-filter-header">
          <text class="list-filter-title">高级筛选</text>
          <uni-icons type="close" size="20" @click="closeFilter"></uni-icons>
        </view>
        <view class="list-filter-content">
          <view class="list-filter-item">
            <text class="list-filter-label">字典类型</text>
            <uni-easyinput v-model="queryParams.dictType" placeholder="请输入字典类型" :clearable="true"/>
          </view>
          <view class="list-filter-item">
            <text class="list-filter-label">状态</text>
            <BottomSelect v-model="queryParams.status" :options="statusOptions" value-field="value" label-field="text"
                          placeholder="请选择状态" title="选择状态"/>
          </view>
        </view>
        <view class="list-filter-footer">
          <view class="btn btn-reset" @click="handleFilterReset">重置</view>
          <view class="btn btn-confirm" @click="handleFilterConfirm">确定</view>
        </view>
      </view>
    </uni-popup>

    <!-- 操作按钮栏 -->
    <view class="list-action-bar">
      <view class="btn btn-primary" @click="handleAdd" v-if="checkPermission(['system:dict:add'])">
        <uni-icons type="plus" size="14" color="#007aff"/>
        <text>新增</text>
      </view>
      <view class="btn btn-default" @click="handleRefresh">
        <uni-icons type="reload" size="14" color="#666"/>
        <text>刷新</text>
      </view>
      <view class="btn btn-default" @click="handleRefreshCache" v-if="checkPermission(['system:dict:remove'])">
        <uni-icons type="reload" size="14" color="#666"/>
        <text>刷新缓存</text>
      </view>
    </view>

    <!-- 列表 -->
    <view class="list-content">
      <view v-for="type in typeList" :key="type.dictId" class="list-item" @click="handleViewData(type)">
        <view class="list-avatar">
          <uni-icons type="list" size="24" color="#1890ff"/>
        </view>
        <view class="list-info">
          <view class="list-header">
            <text class="list-title">{{ type.dictName }}</text>
            <view class="status-badge" :class="type.status === '0' ? 'status-normal' : 'status-disabled'">
              {{ type.status === '0' ? '正常' : '停用' }}
            </view>
          </view>
          <view class="list-details">
            <view class="detail-item">
              <uni-icons type="list" size="14" color="#999"/>
              <text class="detail-text">编号：{{ type.dictId }}</text>
            </view>
            <view class="detail-item">
              <uni-icons type="apps" size="14" color="#999"/>
              <text class="detail-text">类型：{{ type.dictType }}</text>
            </view>
            <view class="detail-item">
              <uni-icons type="calendar" size="14" color="#999"/>
              <text class="detail-text">{{ parseTime(type.createTime, '{y}-{m}-{d}') }}</text>
            </view>
            <view class="detail-item">
              <uni-icons type="compose" size="14" color="#999"/>
              <text class="detail-text">{{ type.remark || '无' }}</text>
            </view>
          </view>
        </view>
        <view class="list-actions">
          <view class="action-btn action-primary" @click.stop="handleUpdate(type)"
                v-if="checkPermission(['system:dict:edit'])">
            <uni-icons type="compose" size="14" color="#007aff"/>
            <text class="action-text">编辑</text>
          </view>
          <view class="action-btn action-success" @click.stop="handleViewData(type)"
                v-if="checkPermission(['system:dict:list'])">
            <uni-icons type="list" size="14" color="#34c759"/>
            <text class="action-text">数据</text>
          </view>
          <view class="action-btn action-danger" @click.stop="handleDelete(type)"
                v-if="checkPermission(['system:dict:remove'])">
            <uni-icons type="trash" size="14" color="#ff3b30"/>
            <text class="action-text">删除</text>
          </view>
        </view>
      </view>
    </view>

    <view v-if="typeList.length > 0" class="list-load-more">
      <uni-load-more :status="loadStatus" :content-text="loadText" @clickLoadMore="handleLoadMore"/>
    </view>

    <view v-if="!loading && typeList.length === 0" class="list-empty">
      <uni-icons type="list" size="48" color="#ddd"/>
      <text class="list-empty-text">暂无字典类型</text>
      <button class="btn btn-primary" @click="handleAdd" v-if="checkPermission(['system:dict:add'])">添加字典</button>
    </view>
  </view>
</template>

<script setup>
import {getCurrentInstance, onMounted, reactive, ref} from 'vue'
import {delType, listType, refreshCache} from '@/api/system/dict/type'
import {parseTime} from '@/utils/ruoyi'

import {usePermission} from '@/utils/permission'
import {BottomSelect} from '@/components/select'

const {proxy} = getCurrentInstance()


const checkPermission = usePermission()

// 数据定义
const typeList = ref([])
const total = ref(0)
const loading = ref(false)
const loadStatus = ref('more')

const loadText = reactive({
  contentdown: '上拉显示更多',
  contentrefresh: '正在加载...',
  contentnomore: '没有更多数据了'
})

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  dictName: '',
  dictType: '',
  status: ''
})

// 选项数据
const statusOptions = [
  {value: '', text: '全部状态'},
  {value: '0', text: '正常'},
  {value: '1', text: '停用'}
]

const filterPopup = ref(null)
let searchTimer = null

// 页面加载
onMounted(() => {
  getList()
})

// 获取字典类型列表
async function getList() {
  if (loading.value) return

  loading.value = true
  loadStatus.value = 'loading'

  try {
    const response = await listType(queryParams)
    if (response.code === 200) {
      const newData = response.rows || []

      if (queryParams.pageNum === 1) {
        typeList.value = newData
      } else {
        typeList.value.push(...newData)
      }

      total.value = response.total || 0

      if (typeList.value.length >= total.value) {
        loadStatus.value = 'noMore'
      } else {
        loadStatus.value = 'more'
      }
    }
  } catch (error) {
    console.error('获取字典类型列表失败:', error)
    proxy.$modal.showToast('获取字典类型列表失败')
    loadStatus.value = 'more'
  } finally {
    loading.value = false
  }
}

function toggleFilter() {
  filterPopup.value.open()
}

function closeFilter() {
  filterPopup.value.close()
}

function handleFilterConfirm() {
  closeFilter();
  handleQuery()
}

function handleFilterReset() {
  Object.assign(queryParams, {pageNum: 1, pageSize: 10, dictName: '', dictType: '', status: ''})
}

function handleSearchInput() {
  if (searchTimer) clearTimeout(searchTimer);
  searchTimer = setTimeout(() => {
    handleQuery()
  }, 300)
}

function handleSearch() {
  handleQuery()
}

function handleClear() {
  queryParams.dictName = '';
  handleQuery()
}

function handleAction(action) {
  switch (action.key) {
    case 'add':
      handleAdd()
      break
    case 'refreshCache':
      handleRefreshCache()
      break
    case 'refresh':
      handleRefresh()
      break
  }
}

function handleDictAction(action) {
  const type = action.data
  switch (action.key) {
    case 'edit':
      handleUpdate(type)
      break
    case 'data':
      handleViewData(type)
      break
    case 'delete':
      handleDelete(type)
      break
  }
}

function handleLoadMore() {
  if (loadStatus.value === 'more') {
    queryParams.pageNum++
    getList()
  }
}

// 查询
function handleQuery() {
  queryParams.pageNum = 1
  typeList.value = []
  getList()
}

// 业务操作方法
function handleAdd() {
  uni.navigateTo({
    url: `/pages_system/dict/type-edit?mode=add`
  })
}

function handleUpdate(type) {
  uni.navigateTo({
    url: `/pages_system/dict/type-edit?mode=edit&dictId=${type.dictId}`
  })
}

function handleViewData(type) {
  uni.navigateTo({
    url: `/pages_system/dict/data?dictType=${type.dictType}&dictName=${type.dictName}`
  })
}

async function handleDelete(type) {
  try {
    await proxy.$modal.confirm(`确认要删除字典类型"${type.dictName}"吗？`)

    const response = await delType(type.dictId)
    if (response.code === 200) {
      proxy.$modal.showToast('删除成功')
      handleQuery()
    }
  } catch (error) {
    console.error('删除字典类型失败:', error)
  }
}

async function handleRefreshCache() {
  try {
    await proxy.$modal.confirm('确认要刷新字典缓存吗？')

    const response = await refreshCache()
    if (response.code === 200) {
      proxy.$modal.showToast('刷新缓存成功')
    }
  } catch (error) {
    console.error('刷新缓存失败:', error)
  }
}

function handleRefresh() {
  handleQuery()
}
</script>

<style lang="scss" scoped>
@import '@/styles/list-page.scss';
</style>